﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Jbe.TestSuite.TestDevices.Interface;
using Microsoft.Practices.Composite.Regions;
using System.Windows.Controls.Primitives;
using Jbe.TestSuite.TestDevices.Manager.Applications;
using Microsoft.Practices.Composite.Presentation.Regions;

namespace Jbe.TestSuite.TestDevices.Manager.Presentation
{
    /// <summary>
    /// Interaction logic for TestDevicesView.xaml
    /// </summary>
    public partial class TestDevicesView : UserControl, ITestDevicesView
    {
        public TestDevicesView(IRegionManager regionManager)
        {
            InitializeComponent();

            // INFO: The RegionManager needs to be registered with the context menu via code. 
            //       Registration in XAML this doesn't work (see CodePlex CompositeWPF forum).
            RegionManager.SetRegionManager(newButton.ContextMenu, regionManager);
            newButton.ContextMenuOpening += NewButtonContextMenuOpening;
            newButton.PreviewMouseLeftButtonUp += NewButtonPreviewMouseLeftButtonUp;
        }

        private void NewButtonContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            newButton.ContextMenu.IsOpen = false;
            e.Handled = true;
        }

        private void NewButtonPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (newButton.ContextMenu != null)
            {
                newButton.ContextMenu.Placement = PlacementMode.Bottom;
                newButton.ContextMenu.PlacementTarget = newButton;
                newButton.ContextMenu.IsOpen = true;
            }
        }

        // INFO: In this case I need code-behind code because I'm not able to bind SelectedItems to a collection provided by the PresentationModel

        public IEnumerable<IControlView> SelectedControlViews { get { return controlDevicesList.SelectedItems.Cast<IControlView>(); } }

        public TestDevicesPresentationModel Model { get; set; }

        
        private void ControlDevicesListSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Model.ControlViewsSelectionChanged();
        }

        private void ControlDevicesListMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Model.OpenDeviceCommand.Execute(null);
        }
    }
}
